#!/usr/bin/env python
import compizconfig
context = compizconfig.Context()

def CatSortCompare(v1, v2):
    if v1 == v2:
        return cmp(v1, v2)
    if context.Plugins['core'].Category == v1:
        return cmp('', v2 or 'zzzzzzzz')
    if context.Plugins['core'].Category == v2:
        return cmp(v1 or 'zzzzzzz', '')
    return cmp(v1 or 'zzzzzzzz', v2 or 'zzzzzzzz')
    
categories = list(sorted(context.Categories, CatSortCompare))
plugins = list(context.Plugins)

categInfo = []
pluginInfo = []
categInfo.append(dict((k, v) for (v, k) in enumerate(categories)))
categInfo[0]["allGroups"] = categories
categInfo[0]["activePlugins"] = list(context.Plugins['core'].Display['active_plugins'].Value)

for categ in sorted(context.Categories, CatSortCompare):
	allPlugins = {}
	thePlugins = []
	
	for plugin in context.Categories[categ]:
		thePlugins.append({"ShortDesc" : plugin.ShortDesc, "Name" : plugin.Name, "LongDesc" : plugin.LongDesc, "isEnabled" : plugin.Enabled})
		
	allPlugins["plugins"] = thePlugins
	allPlugins["allPlugins"] = list(p.ShortDesc for p in context.Categories[categ])
	pluginInfo.append(allPlugins)
	
def getPluginInfo():
	return pluginInfo
	
def getCategInfo():
	return categInfo

services = {
	'getPluginInfo': getPluginInfo,
	'getCategInfo': getCategInfo
}
    
if __name__ == '__main__':
    from pyamf.remoting.wsgigateway import WSGIGateway
    from wsgiref import simple_server

    gw = WSGIGateway(services)

    httpd = simple_server.WSGIServer(
        ('localhost', 8000),
        simple_server.WSGIRequestHandler,
    )

    httpd.set_app(gw)

    print "Running Hello World AMF gateway on http://localhost:8000"

    httpd.serve_forever()
